<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 10/7/14
 * Time: 9:22 AM
 */

namespace Backend\Modules\Video\Controllers;

use Common\library\Common;
use Library\Constant\Constant;
use Phalcon\Paginator\Adapter\QueryBuilder as Paginator;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Backend\Modules\Video\Models\Video;
use Backend\Modules\Video\Models\VideoGroup;
use Backend\Modules\Video\Forms\FormSeachVideo;
use Backend\Modules\Video\Models\Artist ;
use Backend\Modules\Video\Forms\FormSearchArtist;
use Backend\Modules\Video\Forms\FormSearchVideoGroup;

class AjaxVideoGroupController extends \BackendController
{
    public function loadArtistAction($videoGroupId)
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));
        $artistType = $this->request->get('type') ? $this->request->get('type') : Artist::ACTOR;

        $artists = $this->modelsManager->createBuilder()
            ->from(array('artist' => 'Common\Models\Videos\Artist'))
            ->groupBy("artist.id")
            ->where("artist_type = $artistType")
            ->orderBy('artist.id');

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'builder'  => $artists,
                'limit' => 20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => '&page={%page_number}',
            )
        );
        $this->view->pager = $pager;
        $this->view->artistType = $artistType;
        $this->view->videoGroupId = $videoGroupId;
        $this->view->formSearchArtist = new FormSearchArtist();
        if($artistType == Artist::DIRECTOR)
        {
            $this->view->render("common", "modal/modal_director");
            return ;
        }
        $this->view->render("common", "modal/modal_actor");
    }

    public function loadVideoAction($videoGroupId)
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));

        $videos = Video::find();

        $formSearchVideo = new FormSeachVideo();

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'data'  => $videos,
                'limit' => Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 5,
                'urlMask'     => '',
            )
        );
        $this->view->objectType = $this->request->get('object_type');
        $this->view->pager = $pager;
        $this->view->videoGroupId = $videoGroupId;
        $this->view->formSearchVideo = $formSearchVideo;
        $this->view->render("ajax", "modal/modal_video");
    }

    public function seachVideoAction()
    {
        if($this->request->isAjax())
        {
            $this->view->setTemplateAfter('empty');

            $currentPage = abs($this->request->getQuery('page', 'int', 1));

            //$videos = Video::find();
            $sqlWhere = '1 = 1';
            $conditionsWhere = array();

            if($this->request->hasPost('id') && $this->request->getPost('id'))
            {
                $sqlWhere .= ' AND video.id = :id:';
                $conditionsWhere['id'] = $this->request->getPost('id');
            }

            if($this->request->hasPost('name') && $this->request->getPost('name'))
            {
                $sqlWhere .= ' AND videoDescription.name LIKE :name:';
                $conditionsWhere['name'] = '%' . $this->request->getPost('name') . '%';
            }

            if($this->request->hasPost('category_id') && $this->request->getPost('category_id' , 'int') > 0)
            {
                $sqlWhere .= ' AND videoCategoryLink.category_id = :category_id:';
                $conditionsWhere['category_id'] = $this->request->getPost('category_id');
            }

            if($this->request->hasPost('national_id') && $this->request->getPost('national_id' , 'int') > 0)
            {
                $sqlWhere .= ' AND videoDescription.national_id = :national_id:';
                $conditionsWhere['national_id'] = $this->request->getPost('national_id' , 'int');
            }

            $videos = $this->modelsManager->createBuilder()
                ->from(array('video' => '\Backend\Modules\Video\Models\Video'))
                ->groupBy("video.id")
                ->join('\Backend\Modules\Video\Models\VideoDescription' , 'videoDescription.video_id = video.id' , 'videoDescription')
                ->join('\Backend\Modules\Video\Models\VideoCategoryLink' , 'videoCategoryLink.video_id = video.id' , 'videoCategoryLink')
                ->limit(Constant::ITEM_PER_PAGE_20)
                ->where($sqlWhere , $conditionsWhere)
                ->orderBy('video.id')
                ->getQuery()
                ->execute();

            if ($currentPage == 0) {
                $currentPage = 1;
            }

            $pager = new Pager(
                new Paginator(array(
                    'data'  => $videos,
                    'limit' => Constant::ITEM_PER_PAGE_20,
                    'page'  => $currentPage,
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 5,
                    'urlMask'     => '',
                )
            );
            $this->view->pager = $pager;
            $this->view->render("ajax-video-group", "result_search_video");

            $json['success'] = true;
            $json['html'] = $this->view->getContent();
            $this->response->setContent(json_encode($json));
            //Return the response
            return $this->response->send();
        }
    }

    public function addVideoGroupToObjectAction()
    {
        $objectType  = $this->request->get('object_type');
        $objectId  = $this->request->get('object_id');

        if(!$this->request->has('object_type'))
        {
            return $this->response->redirect($this->request->getHTTPReferer());
            return ;
        }

        switch($objectType)
        {
            case 'home-category':
                $homeCategory = \Backend\Modules\Video\Models\HomeCategory::findFirstById($objectId);
                if(!$homeCategory)
                {
                    return $this->response->redirect($this->request->getHTTPReferer());
                    return ;
                }

                if($this->request->hasPost('selectVideoGroup'))
                {
                    $selectVideoGroups = $this->request->getPost('selectVideoGroup');
                    $data = array();
                    foreach($selectVideoGroups as $videoGroupId)
                    {
                        $checkVideoGroupHaveHomeVideoGroup = \Backend\Modules\Video\Models\HomeVideo::find(array(
                            "object_id = $videoGroupId AND home_category_id = $objectId AND object_type = 'video_group'"
                        ))->count();
                        if($checkVideoGroupHaveHomeVideoGroup <= 0)
                        {
                            $selectVideoGroup = \Backend\Modules\Video\Models\VideoGroup::findFirstById($videoGroupId);
                            if($selectVideoGroup)
                            {
                                $homeVideo = new \Backend\Modules\Video\Models\HomeVideo();
                                $homeVideo->setHomeCategoryId($objectId);
                                $homeVideo->setObjectId($videoGroupId);
                                $homeVideo->setObjectType('video_group');
                                $homeVideo->setPosition(0);
                                $homeVideo->setStatus('A');
                                if(!$homeVideo->save())
                                {
                                    $this->flash->error($homeVideo->getMessages());
                                }
                            }
                        }
                    }
                }
                break;
            case 'video-poster':
                if($this->request->hasPost('selectVideoGroup'))
                {
                    $selectVideoGroups = $this->request->getPost('selectVideoGroup');
                    $data = array();
                    foreach($selectVideoGroups as $videoGroupId)
                    {
                        $checkVideoGroupHaveVideoPoster = \Backend\Modules\Video\Models\VideoPosterLink::find(array(
                            "object_id = $videoGroupId AND object_type = 'video_group'"
                        ))->count();
                        if($checkVideoGroupHaveHomeVideoGroup <= 0)
                        {
                            $selectVideoGroup = \Backend\Modules\Video\Models\VideoGroup::findFirstById($videoGroupId);
                            if($selectVideoGroup)
                            {
                                $videoPosterLink = new \Backend\Modules\Video\Models\VideoPosterLink();
                                $videoPosterLink->setObjectId($videoGroupId);
                                $videoPosterLink->setObjectType('video_group');
                                $videoPosterLink->setPosition(0);
                                $videoPosterLink->setStatus('A');
                                if(!$videoPosterLink->save())
                                {
                                    $this->flash->error($videoPosterLink->getMessages());
                                }
                            }
                        }
                    }
                }
            break;

            case 'video':
                $video = Video::findFirstById($objectId);
              
                if(!$video)
                {
                    return $this->response->redirect($this->request->getHTTPReferer());
                }

                if($this->request->getPost('selectVideoGroup'))
                {
                    $selectVideoGroup = $this->request->getPost('selectVideoGroup');

                    $data = array();
                    foreach($selectVideoGroup as $videoGroupId)
                    {
                        $checkHaveVideoGroup = \Backend\Modules\Video\Models\VideoGroupLink::find(array(
                            "video_id = $objectId AND video_group_id = $videoGroupId"
                        ))->count();

                        if($checkHaveVideoGroup <= 0)
                        {
                            $selectVideoGroup = \Backend\Modules\Video\Models\VideoGroup::findFirstById($videoGroupId)->toArray();

                            if($selectVideoGroup)
                            {
                                $videoGroupLink = new \Backend\Modules\Video\Models\VideoGroupLink();
                                $videoGroupLink->setVideoId($objectId);
                                $videoGroupLink->setVideoGroupId($videoGroupId);
                                $videoGroupLink->setPosition(0);
                                if(!$videoGroupLink->save())
                                {

                                }
                            }
                        }
                    }
                }
            break;
        }
        return $this->response->redirect($this->request->getHTTPReferer());
    }

    public function loadVideoGroupAction()
    {
        $this->view->setTemplateAfter('empty');

        $currentPage = abs($this->request->getQuery('page', 'int', 1));

        $videoGroups = $this->modelsManager->createBuilder()
            ->from(array('videoGroup' => 'Common\Models\Videos\VideoGroup'))
            ->groupBy("videoGroup.id")
            ->orderBy('videoGroup.id');

        if ($currentPage == 0) {
            $currentPage = 1;
        }

        $pager = new Pager(
            new Paginator(array(
                'builder'  => $videoGroups,
                'limit' => 10,//Constant::ITEM_PER_PAGE_20,
                'page'  => $currentPage,
            )),
            array(
                'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                'rangeLength' => 10,
                'urlMask'     => '&page={%page_number}',
            )
        );
        $this->view->pager = $pager;
        $this->view->objectId = $this->request->get('object_id') ? $this->request->get('object_id') : 0;
        $this->view->objectType = $this->request->get('object_type');
        $this->view->formSearchVideoGroup = new FormSearchVideoGroup();
        $this->view->render("ajax-video-group", "modal/modal_video_group");
    }

    public function searchVideoGroupAction()
    {
        $json['success'] = false;

        if($this->request->isAjax())
        {
            $this->view->setTemplateAfter('empty');

            $currentPage = abs($this->request->getPost('page', 'int', 1));

            $videoGroup = new VideoGroup();
            $videoGroupBuilder = $videoGroup->queryBuilderSeachVideo($this->request->get());

            if ($currentPage == 0) {
                $currentPage = 1;
            }

            $pager = new Pager(
                new Paginator(array(
                    'builder'  => $videoGroupBuilder,
                    'limit' => 5,//Constant::ITEM_PER_PAGE_20,
                    'page'  => $currentPage,
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 5,
                    'urlMask'     => '&page={%page_number}',
                )
            );
            $this->view->pager = $pager;
            $this->view->render("ajax-video-group", "result_search_video_group");

            $json['success'] = true;
            $json['html'] = $this->view->getContent();
            $this->response->setContent(json_encode($json));
            //Return the response
            return $this->response->send();
        }
        echo json_encode($json);
    }

    public function deleteVideoGroupFromObjectAction()
    {
        if(!$this->request->has('object_type'))
        {
            return ;
        }
        $objectType  = $this->request->get('object_type');
        switch($objectType)
        {
            case 'home-category':
                $objectId = $this->request->get('object_id');
                if($this->request->hasPost('selectedVideoGroupRemove'))
                {
                    $selectedVideosGroups = $this->request->getPost('selectedVideoGroupRemove');
                    $data = array();
                    foreach($selectedVideosGroups as $videoGroupId)
                    {
                        $homeVideo = \Common\Models\Videos\HomeVideo::find(array(
                            "home_category_id = $objectId AND object_id = $videoGroupId AND object_type = 'video_group'"
                        ))->getFirst();
                        if($homeVideo)
                        {
                            $homeVideo->delete();
                        }
                    }
                } 
            break;
        }
        return $this->response->redirect($this->request->getHTTPReferer());
    }
} 